<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2">
<meta name="theme-color" content="#222">
<meta name="generator" content="Hexo 5.2.0">


  <link rel="apple-touch-icon" sizes="180x180" href="/murmur/images/apple-touch-icon-next.png">
  <link rel="icon" type="image/png" sizes="32x32" href="/murmur/images/favicon-32x32-next.png">
  <link rel="icon" type="image/png" sizes="16x16" href="/murmur/images/favicon-16x16-next.png">
  <link rel="mask-icon" href="/murmur/images/logo.svg" color="#222">

<link rel="stylesheet" href="/murmur/css/main.css">



<link rel="stylesheet" href="//cdn.jsdelivr.net/npm/@fortawesome/fontawesome-free@5.15.1/css/all.min.css">
  <link rel="stylesheet" href="//cdn.jsdelivr.net/npm/animate.css@3.1.1/animate.min.css">
  <link rel="stylesheet" href="//cdn.jsdelivr.net/npm/nprogress@0.2.0/nprogress.css">
  <script src="//cdn.jsdelivr.net/npm/nprogress@0.2.0/nprogress.js"></script>

<script class="hexo-configurations">
    var NexT = window.NexT || {};
    var CONFIG = {"hostname":"gitee.com","root":"/murmur/","scheme":"Gemini","version":"8.0.2","exturl":false,"sidebar":{"position":"left","display":"post","padding":18,"offset":12},"copycode":true,"bookmark":{"enable":false,"color":"#222","save":"auto"},"fancybox":false,"mediumzoom":false,"lazyload":false,"pangu":false,"comments":{"style":"tabs","active":"disqus","storage":true,"lazyload":false,"nav":null},"motion":{"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"fadeInDown","post_body":"fadeInDown","coll_header":"fadeInLeft","sidebar":"fadeInUp"}},"prism":false,"i18n":{"placeholder":"搜索...","empty":"没有找到任何搜索结果：${query}","hits_time":"找到 ${hits} 个搜索结果（用时 ${time} 毫秒）","hits":"找到 ${hits} 个搜索结果"}};
  </script>

  <meta name="description" content="什么？!Vuex Store的数据，只能在Vue组件使用？我独立JS文件是不配用吗？">
<meta property="og:type" content="article">
<meta property="og:title" content="没有Vue的computed，独立JS文件怎么使用和监听VuexStore数据">
<meta property="og:url" content="https://gitee.com/lianghuilin/murmur.git/crush_notes/%E6%B2%A1%E6%9C%89Vue%E7%9A%84computed%EF%BC%8C%E7%8B%AC%E7%AB%8BJS%E6%96%87%E4%BB%B6%E6%80%8E%E4%B9%88%E4%BD%BF%E7%94%A8%E5%92%8C%E7%9B%91%E5%90%ACVuexStore%E6%95%B0%E6%8D%AE/index.html">
<meta property="og:site_name" content="汇话板">
<meta property="og:description" content="什么？!Vuex Store的数据，只能在Vue组件使用？我独立JS文件是不配用吗？">
<meta property="og:locale" content="zh_CN">
<meta property="article:published_time" content="2022-04-19T15:00:12.000Z">
<meta property="article:modified_time" content="2022-04-20T15:09:47.910Z">
<meta property="article:author" content="William Leung">
<meta name="twitter:card" content="summary">


<link rel="canonical" href="https://gitee.com/lianghuilin/murmur.git/crush_notes/%E6%B2%A1%E6%9C%89Vue%E7%9A%84computed%EF%BC%8C%E7%8B%AC%E7%AB%8BJS%E6%96%87%E4%BB%B6%E6%80%8E%E4%B9%88%E4%BD%BF%E7%94%A8%E5%92%8C%E7%9B%91%E5%90%ACVuexStore%E6%95%B0%E6%8D%AE/">


<script class="page-configurations">
  // https://hexo.io/docs/variables.html
  CONFIG.page = {
    sidebar: "",
    isHome : false,
    isPost : true,
    lang   : 'zh-CN'
  };
</script>

  <title>没有Vue的computed，独立JS文件怎么使用和监听VuexStore数据 | 汇话板</title>
  


  <script>
    var _hmt = _hmt || [];
    (function() {
      var hm = document.createElement("script");
      hm.src = "https://hm.baidu.com/hm.js?a49081c570a782a242cdf6e19e1a584d";
      var s = document.getElementsByTagName("script")[0];
      s.parentNode.insertBefore(hm, s);
    })();
  </script>




  <noscript>
  <style>
  body { margin-top: 2rem; }

  .use-motion .menu-item,
  .use-motion .sidebar,
  .use-motion .post-block,
  .use-motion .pagination,
  .use-motion .comments,
  .use-motion .post-header,
  .use-motion .post-body,
  .use-motion .collection-header {
    visibility: visible;
  }

  .use-motion .header,
  .use-motion .site-brand-container .toggle,
  .use-motion .footer { opacity: initial; }

  .use-motion .site-title,
  .use-motion .site-subtitle,
  .use-motion .custom-logo-image {
    opacity: initial;
    top: initial;
  }

  .use-motion .logo-line {
    transform: scaleX(1);
  }

  .search-pop-overlay, .sidebar-nav { display: none; }
  .sidebar-panel { display: block; }
  </style>
</noscript>

</head>

<body itemscope itemtype="http://schema.org/WebPage" class="use-motion">
  <div class="headband"></div>

  <main class="main">
    <header class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-container">
  <div class="site-nav-toggle">
    <div class="toggle" aria-label="切换导航栏">
        <span class="toggle-line"></span>
        <span class="toggle-line"></span>
        <span class="toggle-line"></span>
    </div>
  </div>

  <div class="site-meta">

    <a href="/murmur/" class="brand" rel="start">
      <i class="logo-line"></i>
      <h1 class="site-title">汇话板</h1>
      <i class="logo-line"></i>
    </a>
      <p class="site-subtitle" itemprop="description">设定目标，放慢步调，用温和的力量自我改革</p>
  </div>

  <div class="site-nav-right">
    <div class="toggle popup-trigger">
    </div>
  </div>
</div>



<nav class="site-nav">
  <ul class="main-menu menu">
        <li class="menu-item menu-item-home">

    <a href="/murmur/" rel="section"><i class="fa fa-home fa-fw"></i>首页</a>

  </li>
        <li class="menu-item menu-item-categories">

    <a href="/murmur/categories/" rel="section"><i class="fa fa-th fa-fw"></i>分类</a>

  </li>
  </ul>
</nav>




</div>
        
  
  <div class="toggle sidebar-toggle">
    <span class="toggle-line"></span>
    <span class="toggle-line"></span>
    <span class="toggle-line"></span>
  </div>

  <aside class="sidebar">

    <div class="sidebar-inner sidebar-nav-active sidebar-toc-active">
      <ul class="sidebar-nav">
        <li class="sidebar-nav-toc">
          文章目录
        </li>
        <li class="sidebar-nav-overview">
          站点概览
        </li>
      </ul>

      <div class="sidebar-panel-container">
        <!--noindex-->
        <section class="post-toc-wrap sidebar-panel">
            <div class="post-toc animated"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#%E4%BB%A3%E7%A0%81%E6%9C%80%E5%B0%8F%E7%B2%92%E5%BA%A6%E4%B8%8D%E5%9C%A8Vue%E7%BB%84%E4%BB%B6%EF%BC%8C%E5%9C%A8JS%E6%96%87%E4%BB%B6"><span class="nav-number">1.</span> <span class="nav-text">代码最小粒度不在Vue组件，在JS文件</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E4%B8%9A%E5%8A%A1%E8%83%8C%E6%99%AF"><span class="nav-number">2.</span> <span class="nav-text">业务背景</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E9%97%AE%E9%A2%98%E6%8F%8F%E8%BF%B0"><span class="nav-number">3.</span> <span class="nav-text">问题描述</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E6%80%9D%E8%B7%AF1%EF%BC%9A%E5%80%9F%E5%8A%A9EvenBus%E8%BF%9B%E8%A1%8C%E9%80%9A%E7%9F%A5-%E4%B8%8D%E6%8E%A8%E8%8D%90"><span class="nav-number">4.</span> <span class="nav-text">思路1：借助EvenBus进行通知(不推荐)</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E6%80%9D%E8%B7%AF2%EF%BC%9AStore-watch%E7%9B%91%E5%90%AC-%E6%8E%A8%E8%8D%90"><span class="nav-number">5.</span> <span class="nav-text">思路2：Store.watch监听(推荐)</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E5%8F%82%E8%80%83"><span class="nav-number">6.</span> <span class="nav-text">参考</span></a></li></ol></div>
        </section>
        <!--/noindex-->

        <section class="site-overview-wrap sidebar-panel">
          <div class="site-author site-overview-item animated" itemprop="author" itemscope itemtype="http://schema.org/Person">
  <p class="site-author-name" itemprop="name">William Leung</p>
  <div class="site-description" itemprop="description"></div>
</div>
<div class="site-state-wrap site-overview-item animated">
  <nav class="site-state">
      <div class="site-state-item site-state-posts">
          <a href="/murmur/archives">
          <span class="site-state-item-count">43</span>
          <span class="site-state-item-name">文章</span>
        </a>
      </div>
      <div class="site-state-item site-state-categories">
            <a href="/murmur/categories/">
          
        <span class="site-state-item-count">9</span>
        <span class="site-state-item-name">分类</span></a>
      </div>
      <div class="site-state-item site-state-tags">
            <a href="/murmur/tags/">
        <span class="site-state-item-count">1</span>
        <span class="site-state-item-name">标签</span></a>
      </div>
  </nav>
</div>



        </section>
      </div>
    </div>
  </aside>
  <div class="sidebar-dimmer"></div>


    </header>

    
  <div class="back-to-top">
    <i class="fa fa-arrow-up"></i>
    <span>0%</span>
  </div>

<noscript>
  <div class="noscript-warning">Theme NexT works best with JavaScript enabled</div>
</noscript>


    <div class="main-inner post posts-expand">
      

      

  


<div class="post-block">
  
  

  <article itemscope itemtype="http://schema.org/Article" class="post-content" lang="zh-CN">
    <link itemprop="mainEntityOfPage" href="https://gitee.com/lianghuilin/murmur.git/crush_notes/%E6%B2%A1%E6%9C%89Vue%E7%9A%84computed%EF%BC%8C%E7%8B%AC%E7%AB%8BJS%E6%96%87%E4%BB%B6%E6%80%8E%E4%B9%88%E4%BD%BF%E7%94%A8%E5%92%8C%E7%9B%91%E5%90%ACVuexStore%E6%95%B0%E6%8D%AE/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/murmur/images/avatar.gif">
      <meta itemprop="name" content="William Leung">
      <meta itemprop="description" content="">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="汇话板">
    </span>
      <header class="post-header">
        <h1 class="post-title" itemprop="name headline">
          没有Vue的computed，独立JS文件怎么使用和监听VuexStore数据
        </h1>

        <div class="post-meta-container">
          <div class="post-meta">
    <span class="post-meta-item">
      <span class="post-meta-item-icon">
        <i class="far fa-calendar"></i>
      </span>
      <span class="post-meta-item-text">发表于</span>

      <time title="创建时间：2022-04-19 23:00:12" itemprop="dateCreated datePublished" datetime="2022-04-19T23:00:12+08:00">2022-04-19</time>
    </span>
      <span class="post-meta-item">
        <span class="post-meta-item-icon">
          <i class="far fa-calendar-check"></i>
        </span>
        <span class="post-meta-item-text">更新于</span>
        <time title="修改时间：2022-04-20 23:09:47" itemprop="dateModified" datetime="2022-04-20T23:09:47+08:00">2022-04-20</time>
      </span>
    <span class="post-meta-item">
      <span class="post-meta-item-icon">
        <i class="far fa-folder"></i>
      </span>
      <span class="post-meta-item-text">分类于</span>
        <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
          <a href="/murmur/categories/%E9%97%AA%E5%BF%B5%E7%AC%94%E8%AE%B0/" itemprop="url" rel="index"><span itemprop="name">闪念笔记</span></a>
        </span>
    </span>

  
    <span class="post-meta-item" title="本文字数">
      <span class="post-meta-item-icon">
        <i class="far fa-file-word"></i>
      </span>
      <span class="post-meta-item-text">本文字数：</span>
      <span>3k</span>
    </span>
    <span class="post-meta-item" title="阅读时长">
      <span class="post-meta-item-icon">
        <i class="far fa-clock"></i>
      </span>
      <span class="post-meta-item-text">阅读时长 &asymp;</span>
      <span>3 分钟</span>
    </span>
</div>

            <div class="post-description">什么？!Vuex Store的数据，只能在Vue组件使用？我独立JS文件是不配用吗？</div>
        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody">
        <h2 id="代码最小粒度不在Vue组件，在JS文件"><a href="#代码最小粒度不在Vue组件，在JS文件" class="headerlink" title="代码最小粒度不在Vue组件，在JS文件"></a>代码最小粒度不在Vue组件，在JS文件</h2><p>可能有人会奇怪，代码不都写在Vue组件里面，为什么还要在JS文件使用Vuex数据状态？</p>
<p>不是的，因为随着项目的规模越来越大，职责划分变得尤为重要，不能把所有代码都写在Vue组件中。代码最小划分粒度，可能会是一个个独立的JS文件，通过标准的ESModule来彼此衔接和应用。</p>
<h2 id="业务背景"><a href="#业务背景" class="headerlink" title="业务背景"></a>业务背景</h2><p>Vuex Store的auth模块下，有个<code>authorized</code>状态，用来标识WebSocket连接是否建立且授权通过。</p>
<p>之所以这个标识维护在Vuex，是因为页面需要通过一个图标显示通信是否正常，且允许手动点击来关闭WebSocket连接。</p>
<ul>
<li><code>store/index.js</code></li>
</ul>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> Vue <span class="keyword">from</span> <span class="string">&#x27;vue&#x27;</span></span><br><span class="line"><span class="keyword">import</span> Vuex <span class="keyword">from</span> <span class="string">&#x27;vuex&#x27;</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> auth <span class="keyword">from</span> <span class="string">&#x27;./modules/auth&#x27;</span></span><br><span class="line"></span><br><span class="line">Vue.use(Vuex)</span><br><span class="line"></span><br><span class="line"><span class="keyword">const</span> store = <span class="keyword">new</span> Vuex.Store(&#123;</span><br><span class="line">    modules: &#123;</span><br><span class="line">        auth,</span><br><span class="line">    &#125;,</span><br><span class="line">&#125;)</span><br><span class="line"></span><br><span class="line"><span class="keyword">export</span> <span class="keyword">default</span> store</span><br></pre></td></tr></table></figure>

<ul>
<li><code>store/modules/auth.js</code></li>
</ul>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">export</span> <span class="keyword">default</span> &#123;</span><br><span class="line">    namespaced: <span class="literal">true</span>,</span><br><span class="line">    state: &#123;</span><br><span class="line">        authorized: <span class="literal">false</span>,  <span class="comment">// 标识</span></span><br><span class="line">    &#125;,</span><br><span class="line">    mutations: &#123;</span><br><span class="line">        <span class="function"><span class="title">SET_AUTH</span>(<span class="params">state, authorized</span>)</span> &#123;</span><br><span class="line">            state.authorized = authorized</span><br><span class="line">        &#125;,</span><br><span class="line">    &#125;,</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>同时，有一个<code>neffos.js</code>文件负责进行WebSocket连接，需要引用authorized状态，每当<code>send()</code>方法被调用发送数据时，先要判断authorized为true才发送，否则收集进入消息队列。</p>
<p>还要监听<code>authorized</code>重新为true时，遍历消息队列，依次推送消息。</p>
<ul>
<li><code>websocket/neffos.js</code></li>
</ul>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> store <span class="keyword">from</span> <span class="string">&#x27;@store&#x27;</span></span><br><span class="line"><span class="keyword">const</span> queue = []</span><br><span class="line"></span><br><span class="line"><span class="comment">// 监听authorized为true时，发送消息队列</span></span><br><span class="line"><span class="comment">// if (authorized) &#123;</span></span><br><span class="line"><span class="comment">//     while (queue.length &gt; 0) &#123;</span></span><br><span class="line"><span class="comment">//         const msg = queue[0]</span></span><br><span class="line"><span class="comment">//         this.nsConn.emit(&#x27;message&#x27;, msg)</span></span><br><span class="line"><span class="comment">//         queue.shift()</span></span><br><span class="line"><span class="comment">//         console.log(&#x27;queue emit&#x27;, msg)</span></span><br><span class="line"><span class="comment">//     &#125;</span></span><br><span class="line"><span class="comment">// &#125;</span></span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="comment">/*</span></span><br><span class="line"><span class="comment"> * 发送信息</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="function"><span class="title">send</span>(<span class="params">commandKey, data</span>)</span> &#123;</span><br><span class="line">    <span class="keyword">const</span> msg = <span class="built_in">JSON</span>.stringify(commandKey, data)</span><br><span class="line">    <span class="comment">// 将标识放在方法体内，每次调用都获取最新的</span></span><br><span class="line">    <span class="keyword">const</span> &#123; authorized &#125; = store.state.auth</span><br><span class="line"></span><br><span class="line">    <span class="keyword">if</span> (authorized &amp;&amp; <span class="built_in">this</span>.nsConn) &#123;</span><br><span class="line">        <span class="built_in">this</span>.nsConn.emit(<span class="string">&#x27;message&#x27;</span>, msg)</span><br><span class="line">        <span class="built_in">console</span>.info(<span class="string">&#x27;neffos send&#x27;</span>, msg)</span><br><span class="line">    &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">        queue.push(msg)</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h2 id="问题描述"><a href="#问题描述" class="headerlink" title="问题描述"></a>问题描述</h2><p>如果上述代码在Vue组件中，一切都好办，我们可以把<code>authorized</code>挂载到<code>computed</code>中，还可以通过<code>watch</code>来监听数据的变化。</p>
<p>但是WebSocket只负责通信事宜，和视图无关的，理应封装在独立js文件，这样后期还可以迁移到jQuery或者React项目。</p>
<p>而问题就在于，将<code>store.state</code>赋值给独立js文件中的变量，是不具备响应式的，且无法监听它是否发生了变化。</p>
<h2 id="思路1：借助EvenBus进行通知-不推荐"><a href="#思路1：借助EvenBus进行通知-不推荐" class="headerlink" title="思路1：借助EvenBus进行通知(不推荐)"></a>思路1：借助EvenBus进行通知(不推荐)</h2><ul>
<li><code>store/modules/auth.js</code></li>
</ul>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 引入事件总栈</span></span><br><span class="line"><span class="keyword">import</span> EventBus <span class="keyword">from</span> <span class="string">&#x27;@event-bus&#x27;</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">export</span> <span class="keyword">default</span> &#123;</span><br><span class="line">    namespaced: <span class="literal">true</span>,</span><br><span class="line">    state: &#123;</span><br><span class="line">        authorized: <span class="literal">false</span>,</span><br><span class="line">    &#125;,</span><br><span class="line">    mutations: &#123;</span><br><span class="line">        <span class="function"><span class="title">SET_AUTH</span>(<span class="params">state, authorized</span>)</span> &#123;</span><br><span class="line">            state.authorized = authorized</span><br><span class="line">            <span class="comment">// 当赋值为true时，发送通知</span></span><br><span class="line">            <span class="keyword">if</span>(authorized)&#123;</span><br><span class="line">                EventBus.emit(<span class="string">&#x27;authSuccess&#x27;</span>)</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;,</span><br><span class="line">    &#125;,</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<ul>
<li><code>websocket/neffos.js</code></li>
</ul>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> store <span class="keyword">from</span> <span class="string">&#x27;@store&#x27;</span></span><br><span class="line"><span class="keyword">import</span> EventBus <span class="keyword">from</span> <span class="string">&#x27;@event-bus&#x27;</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">const</span> queue = []</span><br><span class="line"></span><br><span class="line"><span class="comment">// 监听authorized为true时，发送消息队列</span></span><br><span class="line">EventBus.on(<span class="string">&#x27;authSuccess&#x27;</span>, <span class="function">() =&gt;</span> &#123;</span><br><span class="line">    <span class="keyword">while</span> (queue.length &gt; <span class="number">0</span>) &#123;</span><br><span class="line">        <span class="keyword">const</span> msg = queue[<span class="number">0</span>]</span><br><span class="line">        <span class="built_in">this</span>.nsConn.emit(<span class="string">&#x27;message&#x27;</span>, msg)</span><br><span class="line">        queue.shift()</span><br><span class="line">        <span class="built_in">console</span>.log(<span class="string">&#x27;queue emit&#x27;</span>, msg)</span><br><span class="line">    &#125;</span><br><span class="line">&#125;)</span><br></pre></td></tr></table></figure>

<h2 id="思路2：Store-watch监听-推荐"><a href="#思路2：Store-watch监听-推荐" class="headerlink" title="思路2：Store.watch监听(推荐)"></a>思路2：Store.watch监听(推荐)</h2><p>其实Vuex Store实例本身就提供了<code>watch</code>方法，用于监听state或者getters数据的变化。这样就不用增加EventBus的订阅，少写代码减少程序的复杂度，也让逻辑更清晰。</p>
<ul>
<li><code>websocket/neffos.js</code></li>
</ul>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> store <span class="keyword">from</span> <span class="string">&#x27;@store&#x27;</span></span><br><span class="line"><span class="keyword">import</span> EventBus <span class="keyword">from</span> <span class="string">&#x27;@event-bus&#x27;</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">const</span> queue = []</span><br><span class="line"></span><br><span class="line"><span class="comment">// 监听authorized为true时，发送消息队列</span></span><br><span class="line">store.watch(</span><br><span class="line">    <span class="comment">// 第一个参数是箭头函数，用来选择你要监听的数据</span></span><br><span class="line">    (state,getters) =&gt; state.auth.authorized,</span><br><span class="line">    <span class="comment">// 第二参数也是箭头函数，是数据改变后的回调监听</span></span><br><span class="line">    authorized =&gt; &#123;</span><br><span class="line">        <span class="keyword">if</span> (authorized) &#123;</span><br><span class="line">            <span class="keyword">while</span> (queue.length &gt; <span class="number">0</span>) &#123;</span><br><span class="line">                <span class="comment">// 发一个删一个，确保发送顺序</span></span><br><span class="line">                <span class="keyword">const</span> msg = queue[<span class="number">0</span>]</span><br><span class="line">                <span class="built_in">this</span>.nsConn.emit(<span class="string">&#x27;message&#x27;</span>, msg)</span><br><span class="line">                queue.shift()</span><br><span class="line">                <span class="built_in">console</span>.log(<span class="string">&#x27;queue emit&#x27;</span>, msg)</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;,</span><br><span class="line">)</span><br></pre></td></tr></table></figure>

<h2 id="参考"><a href="#参考" class="headerlink" title="参考"></a>参考</h2><ul>
<li><a target="_blank" rel="noopener" href="https://v3.vuex.vuejs.org/zh/api/#vuex-store">Vuex官网文档 - Store</a></li>
<li><a target="_blank" rel="noopener" href="https://dev.to/viniciuskneves/watch-for-vuex-state-changes-2mgj">Watch for Vuex State changes</a></li>
</ul>

    </div>

    
    
    

    <footer class="post-footer">
          

<div class="post-copyright">
<ul>
  <li class="post-copyright-author">
      <strong>本文作者： </strong>William Leung
  </li>
  <li class="post-copyright-link">
      <strong>本文链接：</strong>
      <a href="https://gitee.com/lianghuilin/murmur.git/crush_notes/%E6%B2%A1%E6%9C%89Vue%E7%9A%84computed%EF%BC%8C%E7%8B%AC%E7%AB%8BJS%E6%96%87%E4%BB%B6%E6%80%8E%E4%B9%88%E4%BD%BF%E7%94%A8%E5%92%8C%E7%9B%91%E5%90%ACVuexStore%E6%95%B0%E6%8D%AE/" title="没有Vue的computed，独立JS文件怎么使用和监听VuexStore数据">https://gitee.com/lianghuilin/murmur.git/crush_notes/没有Vue的computed，独立JS文件怎么使用和监听VuexStore数据/</a>
  </li>
  <li class="post-copyright-license">
    <strong>版权声明： </strong>本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/" rel="noopener" target="_blank"><i class="fab fa-fw fa-creative-commons"></i>BY-NC-SA</a> 许可协议。转载请注明出处！
  </li>
</ul>
</div>


        

          <div class="post-nav">
            <div class="post-nav-item">
                <a href="/murmur/crush_notes/%E4%B8%BA%E4%BB%80%E4%B9%88JS%E5%9F%BA%E7%A1%80%E6%95%B0%E6%8D%AE%E7%B1%BB%E5%9E%8B%E8%A6%81%E6%94%BE%E6%A0%88%E5%86%85%E5%AD%98%EF%BC%9F/" rel="prev" title="为什么JS基础数据类型要放栈内存？">
                  <i class="fa fa-chevron-left"></i> 为什么JS基础数据类型要放栈内存？
                </a>
            </div>
            <div class="post-nav-item">
                <a href="/murmur/crush_notes/Vue%20template+script+scss%E4%B8%AD%E4%BD%BF%E7%94%A8asserts%E8%B7%AF%E5%BE%84%E5%88%AB%E5%90%8D/" rel="next" title="别再../../引assets了，使用路径别名吧">
                  别再../../引assets了，使用路径别名吧 <i class="fa fa-chevron-right"></i>
                </a>
            </div>
          </div>
    </footer>
  </article>
</div>






      

<script>
  window.addEventListener('tabs:register', () => {
    let { activeClass } = CONFIG.comments;
    if (CONFIG.comments.storage) {
      activeClass = localStorage.getItem('comments_active') || activeClass;
    }
    if (activeClass) {
      const activeTab = document.querySelector(`a[href="#comment-${activeClass}"]`);
      if (activeTab) {
        activeTab.click();
      }
    }
  });
  if (CONFIG.comments.storage) {
    window.addEventListener('tabs:click', event => {
      if (!event.target.matches('.tabs-comment .tab-content .tab-pane')) return;
      const commentClass = event.target.classList[1];
      localStorage.setItem('comments_active', commentClass);
    });
  }
</script>

    </div>
  </main>

  <footer class="footer">
    <div class="footer-inner">
      

      

<div class="copyright">
  
  &copy; 
  <span itemprop="copyrightYear">2023</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">William Leung</span>
</div>
<div class="wordcount">
  <span class="post-meta-item">
    <span class="post-meta-item-icon">
      <i class="fa fa-chart-line"></i>
    </span>
    <span title="站点总字数">142k</span>
  </span>
  <span class="post-meta-item">
    <span class="post-meta-item-icon">
      <i class="fa fa-coffee"></i>
    </span>
    <span title="站点阅读时长">2:09</span>
  </span>
</div>
<div class="busuanzi-count">
    <span id="busuanzi_container_site_uv">
      本站访客数<span id="busuanzi_value_site_uv"></span>人次
    </span>
    <span id="busuanzi_container_site_pv">
        本站总访问量<span id="busuanzi_value_site_pv"></span>次
    </span>
</div>
  <div class="powered-by">由 <a href="https://hexo.io/" class="theme-link" rel="noopener" target="_blank">Hexo</a> & <a href="https://theme-next.js.org/" class="theme-link" rel="noopener" target="_blank">NexT.Gemini</a> 强力驱动
  </div>

    </div>
  </footer>

  
  <script src="//cdn.jsdelivr.net/npm/animejs@3.2.1/lib/anime.min.js"></script>
<script src="/murmur/js/utils.js"></script><script src="/murmur/js/motion.js"></script><script src="/murmur/js/next-boot.js"></script>

  
















  <script>
    NProgress.configure({
      showSpinner: true
    });
    NProgress.start();
    document.addEventListener('readystatechange', () => {
      if (document.readyState === 'interactive') {
        NProgress.inc(0.8);
      }
      if (document.readyState === 'complete') {
        NProgress.done();
      }
    });
    document.addEventListener('pjax:send', () => {
      NProgress.start();
    });
    document.addEventListener('pjax:success', () => {
      NProgress.done();
    });
  </script>


  
  <script async src="https://busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>








  

  

</body>
</html>
